package com.crawler.http

import java.util.Date

import akka.actor.{ActorSystem, Props}
import akka.http.scaladsl.server._
import akka.pattern.ask
import akka.stream.ActorMaterializer
import akka.util.Timeout
import com.crawler.actor.{ListenerActor, RouterActor, TaskDBActor}
import com.crawler.message.TaskParamMessage
import com.crawler.proxy.ProxyUtils
import com.crawler.serializers.MyResource
import com.crawler.store.LocalStore
import com.crawler.tables.Tables.TaskRow
import com.crawler.utils.MD5Utils
import com.typesafe.config.ConfigFactory
import org.slf4j.LoggerFactory

import scala.concurrent._
import scala.concurrent.duration._
import scala.util.{Failure, Success}

/**
  * Created by tongtao.zhu on 2016/11/8.
  */
class ApiRoutes extends MyResource{
  val config = ConfigFactory.load()
  val host = config.getString("http.host")
  val port = config.getInt("http.port")

  val log = LoggerFactory.getLogger(this.getClass.getName)
  implicit val system = ActorSystem("crawler-master",ConfigFactory.load().getConfig("ClusterMaster"))
  implicit val materializer = ActorMaterializer()

  system.actorOf(Props[ListenerActor], name = "listenerActor")
  val routerRef = system.actorOf(Props[RouterActor], name = "routerRef")
  system.actorOf(Props[ProxyUtils], name = "proxyUtilsRef")
  system.actorOf(Props[LocalStore], name = "localStore")
  implicit val taskDBRef = system.actorOf(Props[TaskDBActor])
  implicit val executionContext = system.dispatcher
  implicit val timeout = Timeout(10 seconds)

  def routes: Route = pathPrefix("crawler") {
    path("ping") {
      post{
        entity(as[TaskParamMessage]) { task =>
          complete{
            log.info("start a task...")
            val future = Future{taskDBRef ? TaskRow(task.method,task.data,task.host,task.param,task.header,task.source,task.`type`,task.status,task.prior,new Date().getTime,MD5Utils.getMd5String(task))}
            future onComplete {
              case Success(success) =>
              case Failure(failure) =>
            }
            task
          }
        }
      }
    }~
    path("query"){
      get{
        parameter('resource.as[String]){ resource =>
          onSuccess((taskDBRef ? resource).mapTo[List[Tuple2[Int, Long]]]){result =>
            val re = result.map{ ta =>
              if (ta._1 == 1){
                ("已经结束任务总数为：", ta._2)
              }else if (ta._1 == 2){
                ("正在执行任务总数为：", ta._2)
              }else if (ta._1 == 0){
                ("未分配任务总数为：", ta._2)
              }
            }
            complete(re)
          }
        }
      }
    }~
    path("restart"){
      get{
        parameter('resource.as[String]){ resource =>
          complete{
            val future = Future{taskDBRef ? resource}
            future onComplete {
              case Success(success) =>
              case Failure(failure) =>
            }
            resource
          }
        }
      }
    }
  }
}
